package com.monster.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.monster.dao.*;
import com.monster.pojo.Playlist;
import com.monster.pojo.Song;

import java.util.ArrayList;
import java.util.jar.JarInputStream;

public class SongUtil {
    private static SongDao sd = new SongDaoImpl();
    private static SingerDao sid = new SingerDaoImpl();
    private static PlaylistDao pd = new PlaylistDaoImpl();
    private static AlbumDao ad = new AlbumDaoImpl();

    /**
     * 根据关键字类型和id获取所有歌曲信息
     * @param key 关键字，代表类型
     * @param id key类型对应的id
     * @return 歌曲信息集合
     */
    public static ArrayList<Song> getSongs(String key, Long id) {
        ArrayList<Song> songs = new ArrayList<>();
        switch (key) {
            case "song":
                songs.add(sd.getSongById(id));
                break;
            case "playlist":
                Playlist p = new Playlist();
                p.setPlaylistId(id);
                songs = pd.selectSongIdByPlaylistId(p.getPlaylistId());
                break;
            case "album":
                songs = (ArrayList<Song>) ad.selectSongByAlbumId(id);
                break;
            case "singer":
                songs = sid.getSingersBySingerId(id).getSongs();    // 未分页！
                for (int i = 0; i < songs.size(); i++) {
                    songs.set(i, sd.getSongById(songs.get(i).getSongId()));
                }
                break;
            default:
        }
        for (Song s : songs) {
            s.setSingers(sd.listSingersBySongId(s.getSongId()));
        }
        return songs;
    }

    /**
     * 将存有id的JSON数组字符串转化为id的Long集合
     * @param array JSON数组字符串
     * @param key 数组中的JSON的属性名
     * @return id的Long集合
     */
    public static ArrayList<Long> parseJSONtoSongId(String array, String key) {
        ArrayList<Long> songIds = new ArrayList<>();
        JSONArray JArray = JSONArray.parseArray(array);
        for (int i = 0; i < JArray.size(); i++) {
            Object obj = JSONObject.parseObject(JArray.getString(i)).get(key);
            Long songId = Long.parseLong(obj + "");
            songIds.add(songId);
        }
        return songIds;
    }
}
